import 'reflect-metadata';
import { serve } from '@hono/node-server';
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { logger } from 'hono/logger';
import { prettyJSON } from 'hono/pretty-json';
import { secureHeaders } from 'hono/secure-headers';
import { initializeDatabase } from '@weubi/shared';

import { Server as SocketIOServer } from 'socket.io';
import * as dotenv from 'dotenv';

// 导入路由
import { healthRoutes } from './routes/health';
import { taskRoutes } from './routes/tasks';
import { dataRoutes } from './routes/data';
import { authRoutes } from './routes/auth';

// 导入服务
import { setupWebSocket } from './services/websocket';
import { setupQueues } from './services/queue';

// 加载环境变量
import * as path from 'path';
dotenv.config({ path: path.resolve(__dirname, '../../../.env') });

// 创建 Hono 应用
const app = new Hono();

// 全局中间件
app.use('*', cors({
  origin: process.env.NODE_ENV === 'production' 
    ? ['https://your-domain.com'] 
    : ['http://localhost:3000'],
  credentials: true,
}));

app.use('*', logger());
app.use('*', secureHeaders());
app.use('*', prettyJSON());

// API 路由
app.route('/health', healthRoutes);
app.route('/api/auth', authRoutes);
app.route('/api/tasks', taskRoutes);
app.route('/api/data', dataRoutes);

// 根路径
app.get('/', (c) => {
  return c.json({
    name: 'Weubi Crawler API',
    version: '1.0.0',
    description: '高性能多引擎爬虫系统 API',
    timestamp: new Date().toISOString(),
    endpoints: {
      health: '/health',
      auth: '/api/auth',
      tasks: '/api/tasks',
      data: '/api/data',
      docs: '/docs',
    },
  });
});

// 404 处理
app.notFound((c) => {
  return c.json({
    success: false,
    error: 'Not Found',
    message: 'The requested resource was not found',
    timestamp: new Date().toISOString(),
  }, 404);
});

// 错误处理
app.onError((err, c) => {
  console.error('API Error:', err);
  
  return c.json({
    success: false,
    error: 'Internal Server Error',
    message: process.env.NODE_ENV === 'development' ? err.message : 'Something went wrong',
    timestamp: new Date().toISOString(),
  }, 500);
});

// 启动服务器
async function startServer() {
  try {
    // 初始化数据库
    console.log('🔗 Connecting to database...');
    await initializeDatabase();
    
    // 设置消息队列
    console.log('🔄 Setting up message queues...');
    await setupQueues();
    
    // 创建 HTTP 服务器
    const port = parseInt(process.env.API_PORT || '3001');
    const server = serve({
      fetch: app.fetch,
      port,
    });

    // 设置 WebSocket
    const io = new SocketIOServer(server, {
      cors: {
        origin: process.env.NODE_ENV === 'production'
          ? ['https://your-domain.com']
          : ['http://localhost:3000'],
        credentials: true,
      },
    });

    setupWebSocket(io);

    console.log(`🚀 API Server running on http://localhost:${port}`);
    console.log(`📊 WebSocket server ready`);
    console.log(`🎯 Environment: ${process.env.NODE_ENV || 'development'}`);
    
    // 优雅关闭
    process.on('SIGTERM', async () => {
      console.log('🛑 Received SIGTERM, shutting down gracefully...');
      server.close(() => {
        console.log('✅ Server closed');
        process.exit(0);
      });
    });
    
    process.on('SIGINT', async () => {
      console.log('🛑 Received SIGINT, shutting down gracefully...');
      server.close(() => {
        console.log('✅ Server closed');
        process.exit(0);
      });
    });
    
  } catch (error) {
    console.error('❌ Failed to start server:', error);
    process.exit(1);
  }
}

// 启动应用
startServer();
